﻿using System.IO;
using System.Web.Mvc;
using System.Web.Routing;

namespace YuYuKiCms.Framework.Core.Extention
{
    public static class ControllerExtention
    {
        public static ActionResult RedirectToLocal(this Controller ctrl, string returnUrl)
        {
            if (ctrl.Url.IsLocalUrl(returnUrl))
            {
                return new RedirectResult(returnUrl);
            }
            return new RedirectToRouteResult("Default", new RouteValueDictionary(new {controller = "Home"}));
        }

        public static string PartialViewToString(this Controller controller)
        {
            return controller.PartialViewToString(null, null);
        }

        public static string RenderPartialViewToString(this Controller controller, string viewName)
        {
            return controller.PartialViewToString(viewName, null);
        }

        public static string RenderPartialViewToString(this Controller controller, object model)
        {
            return controller.PartialViewToString(null, model);
        }

        public static string PartialViewToString(this Controller controller, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }
            controller.ViewData.Model = model;
            using (var stringWriter = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    stringWriter);
                viewResult.View.Render(viewContext, stringWriter);
                return stringWriter.GetStringBuilder().ToString();
            }
        }
    }
}